﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace RBS.Web.API.Models
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> where T : class
    {
        //实例化EF框架
        readonly ApiContext _db = new ApiContext();

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public T AddEntities(T entity)
        {
            _db.Entry<T>(entity).State = EntityState.Added;
            _db.SaveChanges();
            return entity;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateEntities(T entity)
        {
            _db.Set<T>().Attach(entity);
            _db.Entry<T>(entity).State = EntityState.Modified;
            return _db.SaveChanges() > 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool DeleteEntities(T entity)
        {
            _db.Set<T>().Attach(entity);
            _db.Entry<T>(entity).State = EntityState.Deleted;
            return _db.SaveChanges() > 0;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="wherelambda"></param>
        /// <returns></returns>
        public IQueryable<T> LoadEntities(Func<T, bool> wherelambda)
        {
            return _db.Set<T>().Where<T>(wherelambda).AsQueryable();
        }

       /// <summary>
       /// 分页
       /// </summary>
       /// <typeparam name="S"></typeparam>
       /// <param name="pageSize"></param>
       /// <param name="pageIndex"></param>
       /// <param name="total"></param>
       /// <param name="whereLambda"></param>
       /// <param name="isAsc"></param>
       /// <param name="orderByLambda"></param>
       /// <returns></returns>
        public IQueryable<T> LoadPagerEntities<S>(int pageSize, int pageIndex, out int total,
            Func<T, bool> whereLambda, bool isAsc, Func<T, S> orderByLambda)
        {
            var tempData = _db.Set<T>().Where<T>(whereLambda);

            total = tempData.Count();

            //排序获取当前页的数据
            if (isAsc)
            {
                tempData = tempData.OrderBy<T, S>(orderByLambda).
                      Skip<T>(pageSize * (pageIndex - 1)).
                      Take<T>(pageSize).AsQueryable();
            }
            else
            {
                tempData = tempData.OrderByDescending<T, S>(orderByLambda).
                     Skip<T>(pageSize * (pageIndex - 1)).
                     Take<T>(pageSize).AsQueryable();
            }
            return tempData.AsQueryable();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rows"></param>
        /// <param name="totalPage"></param>
        /// <param name="where"></param>
        /// <param name="orderKey"></param>
        /// <param name="paramss"></param>
        /// <returns></returns>
        public List<T> GetPagedEntitys(int pageIndex, int pageSize, out int rows, out int totalPage, string where, string orderKey, params object[] paramss)
        {

            string sqls = "";
            string tableName = typeof(T).Name;//获取表名
            string sql = string.Format("select *, row_number() over (order by {0} ) as row_number from {1}", string.IsNullOrEmpty(orderKey) ? "Id" : orderKey, tableName);
            string where1 = !string.IsNullOrEmpty(where) ? " where 1=1 " + where : "";
            int tag = (pageIndex - 1) * pageSize;
            sqls = string.Format(@"select top ({0}) * from 
                         ( 
                           {1}
                           {2}
                          )  as t
                         where t.row_number > {3}", pageSize, sql, where1, tag);
            //获取数据
            var list = _db.Database.SqlQuery<T>(sqls, paramss).ToList<T>();

            //通过自定义的class R 取得总页码数和记录数
            string sqlCount = string.Format("select count(1) as Rows from {0} {1}", tableName, where1);
            rows = _db.Database.SqlQuery<R>(sqlCount, paramss).ToList()[0].Rows;
            totalPage = rows % pageSize == 0 ? rows / pageSize : rows / pageSize + 1; 
            return list;

        }
        public class R
        {
            public int Rows { get; set; }
        }
    }



}